﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;

namespace SP2010LanguagePack
{
    public partial class Form1 : Form
    {
        int totalselected = 0;
        int totaldone = 0;
        int downloadingcurrently = 0;
        string currentdownloadlanguagename;
        bool cancelled = false;
        WebClient client = new WebClient();
        int selectedval;

        public Form1()
        {
            InitializeComponent();
        }

        List<string[]> downloadpaths;
        List<string[]> selecteddownloads = new List<string[]>();

        private void button1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.RootFolder=System.Environment.SpecialFolder.DesktopDirectory;
            folderBrowserDialog1.ShowDialog();
            if (folderBrowserDialog1.SelectedPath != "folderBrowserDialog1")
                textBox1.Text = folderBrowserDialog1.SelectedPath;
        }

        public List<string[]> ParseCSV(string path, int max)
        {
            List<string[]> parsedData = new List<string[]>();
            using (StreamReader readFile = new StreamReader(path, System.Text.Encoding.UTF7))
            {
                string line;
                string[] row;
                while ((line = readFile.ReadLine()) != null)
                {
                    char[] delimiters = new char[] { ',' };
                    row = line.Split(delimiters, max);
                    parsedData.Add(row);
                }
            }
            return parsedData;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button3.Enabled = false;
            label1.ForeColor = Color.FromArgb(0, 114, 198);
            downloadpaths = ParseCSV(Application.StartupPath + "//Paths//paths.csv", 2);
            foreach (string[] path in downloadpaths)
            {
                checkedListBox1.Items.Add(path[1]);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            selectedval = comboBox1.SelectedIndex + 1;
            if (selectedval > 0 && selectedval <= 8)
            {
                if (!string.IsNullOrEmpty(textBox1.Text))
                {
                    if (totaldone != 0)
                    {
                        client.Dispose();
                        client = new WebClient();
                    }
                    cancelled = false;
                    totaldone = 0;
                    selecteddownloads.Clear();
                    totalselected = 0;
                    downloadingcurrently = 0;
                    totalselected = checkedListBox1.CheckedIndices.Count;
                    if (totalselected > 0)
                    {
                        label3.Visible = true;
                        progressBar1.Visible = true;
                        button3.Enabled = true;
                        button2.Enabled = false;
                        toolStripStatusLabel2.Text = "Starting downloads of selected language packs, please wait...";

                        client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                        foreach (int selected in checkedListBox1.CheckedIndices)
                        {
                            string[] todownload = downloadpaths[selected];
                            selecteddownloads.Add(todownload);
                        }
                        string[] downloadnow = selecteddownloads[downloadingcurrently];
                        currentdownloadlanguagename = downloadnow[1];
                        string guid = getGuid(selectedval);
                        string urlstring = getDownloadLink(downloadnow[0], getGuid(selectedval));
                        if (!string.IsNullOrEmpty(urlstring))
                        {
                            Uri url = new Uri(urlstring);
                            client.DownloadFileAsync(url, textBox1.Text + "\\" + downloadnow[1] + getFilename(selectedval));
                        }
                        else
                        {
                           downloadNext();
                        }
                    }
                    else
                    {
                        MessageBox.Show("You need to select a language!");
                        toolStripStatusLabel2.Text = "You need to select a language!";
                    }
                }
                else
                {
                    MessageBox.Show("You need to provide a destination folder!");
                    toolStripStatusLabel2.Text = "You need to provide a destination folder!";
                }
            }
            else
            {
                MessageBox.Show("You need to select your download type!");
                toolStripStatusLabel2.Text = "You need to select your download type!";
            }
        }
        void downloadNext()
        {
            downloadingcurrently++;
            totaldone++;
            string[] downloadnow = selecteddownloads[downloadingcurrently];
            currentdownloadlanguagename = downloadnow[1];
            string urlstring = getDownloadLink(downloadnow[0], getGuid(selectedval));
            if (!string.IsNullOrEmpty(urlstring))
            {
                Uri url = new Uri(urlstring);
                client.DownloadFileAsync(url, textBox1.Text + "\\" + downloadnow[1] + getFilename(selectedval));
            }
            else{
                downloadNext();
            }
        }

        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            string sp = (selectedval == 4 || selectedval == 5) ? " SP1 " : (selectedval == 6 || selectedval == 7) ? " SP2 " : String.Empty;
            label3.Text = currentdownloadlanguagename + sp + ": downloaded " + (e.BytesReceived)/1024 + "KB of "+ (e.TotalBytesToReceive)/1024 + "KB. "+ e.ProgressPercentage +" % complete...";
            progressBar1.Value = e.ProgressPercentage;
        }
        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (!cancelled)
            {
                toolStripStatusLabel2.Text = currentdownloadlanguagename + " done.";
                totaldone++;
                if (totaldone < totalselected)
                {
                    downloadingcurrently++;
                    string[] downloadnow = selecteddownloads[downloadingcurrently];
                    currentdownloadlanguagename = downloadnow[1];
                    string urlstring = getDownloadLink(downloadnow[0], getGuid(selectedval));
                    if (!string.IsNullOrEmpty(urlstring))
                    {
                        Uri url = new Uri(urlstring);
                        client.DownloadFileAsync(url, textBox1.Text + "\\" + downloadnow[1] + getFilename(selectedval));
                    }
                    else
                    {
                        downloadNext();
                    }

                    double perc = Convert.ToDouble(totaldone) / Convert.ToDouble(totalselected) * 100;
                    int percentage = Convert.ToInt32(perc);
                    toolStripProgressBar1.Value = percentage;
                }
                else if (totaldone == totalselected)
                {
                    button2.Enabled = true;
                    button3.Enabled = false;
                    label3.Visible = false;
                    progressBar1.Visible = false;
                    toolStripProgressBar1.Value = 0;
                    toolStripStatusLabel2.Text = "Done downloading the language packs.";
                }
            }
            else
            {
                button2.Enabled = true;
                button3.Enabled = false;
                label3.Visible = false;
                progressBar1.Visible = false;
                toolStripStatusLabel2.Text = "Cancelled download.";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            cancelled = true;
            client.CancelAsync();
        }

        private string getGuid(int value)
        {
            switch (value)
            {
                case 1: return "c1fc3611-dd68-48ea-ad8e-b04951cf5b66";
                case 2: return "dd0cadfc-e1ef-4a77-9cda-c08db6e9d305";
                case 3: return "046f16a9-4bce-4149-8679-223755560d54";
                case 4: return "646e311a-aaf3-4d30-b03c-2f3c70d19a22";
                case 5: return "ecdb9e7b-7dba-4ca6-8683-5427925ae955";
                case 6: return "68b5071a-e890-4b1c-b6dc-8493a033e853";
                case 7: return "09fb704c-01fd-4159-be21-c8b230fb9b41";
                case 8: return "b203e608-5c29-45e7-a4a9-a579578ec710";
                default: return "";
            }
        }
        private string getFilename(int value)
        {
            switch (value)
            {
                case 1: return "LanguagePack_2013.img";
                case 2: return "FoundationLanguagePack_2013.exe";
                case 3: return "LanguagePack.exe";
                case 4: return "FoundationLanguagePack.exe";
                case 5: return "LanguagePack_SP1.exe";
                case 6: return "FoundationLanguagePack_SP1.exe";
                case 7: return "LanguagePack_SP2.exe";
                case 8: return "FoundationLanguagePack_SP2.exe";
                default: return "";
            }
        }

        private string getDownloadLink(string language, string guid)
        {
            string ret = "";
            try
            {
                string returned = client.DownloadString("http://www.microsoft.com/downloads/" + language + "/details.aspx?familyid=" + guid);
                if (returned.IndexOf("u=http%3a%2f%2fdownload.microsoft.com") != -1)
                {
                    returned = returned.Substring(returned.IndexOf("u=http%3a%2f%2fdownload.microsoft.com") + 2);
                    returned = returned.Substring(0, returned.IndexOf("\""));
                    if (returned.IndexOf("\'") != -1) returned = returned.Substring(0, returned.IndexOf("\'"));
                    returned = System.Web.HttpUtility.UrlDecode(returned);
                    //MessageBox.Show(returned);
                    ret = returned;
                }
                else if (returned.IndexOf("var downloadFileUrl = \"") != -1)
                {
                    returned = returned.Substring(returned.IndexOf("var downloadFileUrl = \"") + 23);
                    returned = returned.Substring(0, returned.IndexOf("\""));
                    if (returned.IndexOf("\'") != -1) returned = returned.Substring(0, returned.IndexOf("\'"));
                    returned = System.Web.HttpUtility.UrlDecode(returned);
                    //MessageBox.Show(returned);
                    ret = returned;
                }
                else if (returned.IndexOf("bi:fileurl=\"http") != -1)
                {
                    returned = returned.Substring(returned.IndexOf("bi:fileurl=\"http") + 12);
                    returned = returned.Substring(0, returned.IndexOf("\""));
                    if (returned.IndexOf("\'") != -1) returned = returned.Substring(0, returned.IndexOf("\'"));
                    returned = System.Web.HttpUtility.UrlDecode(returned);
                    //MessageBox.Show(returned);
                    ret = returned;
                }
                else
                {
                    string returned2 = client.DownloadString("http://www.microsoft.com/downloads/details.aspx?familyid=" + guid + "&displayLang=" + language);
                    if (returned2.IndexOf("bi:fileurl=\"http") != -1)
                    {
                        returned2 = returned2.Substring(returned2.IndexOf("bi:fileurl=\"http") + 12);
                        returned2 = returned2.Substring(0, returned2.IndexOf("\""));
                        if (returned2.IndexOf("\'") != -1) returned2 = returned2.Substring(0, returned2.IndexOf("\'"));
                        returned2 = System.Web.HttpUtility.UrlDecode(returned2);
                        //MessageBox.Show(returned2);
                        ret = returned2;
                    }
                    else if (returned2.IndexOf("var downloadFileUrl = \"") != -1)
                    {
                        returned2 = returned2.Substring(returned2.IndexOf("var downloadFileUrl = \"") + 23);
                        returned2 = returned2.Substring(0, returned2.IndexOf("\""));
                        if (returned2.IndexOf("\'") != -1) returned2 = returned2.Substring(0, returned2.IndexOf("\'"));
                        returned2 = System.Web.HttpUtility.UrlDecode(returned2);
                        //MessageBox.Show(returned);
                        ret = returned2;
                    }
                    else
                    {
                        returned2 = returned2.Substring(returned2.IndexOf("if (g_IsIE) {window.open(\'http://download.microsoft.com") + 26);
                        returned2 = returned2.Substring(0, returned2.IndexOf("\""));
                        if (returned2.IndexOf("\'") != -1) returned2 = returned2.Substring(0, returned2.IndexOf("\'"));
                        returned2 = System.Web.HttpUtility.UrlDecode(returned2);
                        //MessageBox.Show(returned2);  
                        ret = returned2;
                    }
                }
                //returned = returned.Substring(returned.IndexOf("u=http%3a%2f%2fdownload.microsoft.com") + 2);
                //returned = returned.Substring(0, returned.IndexOf("\""));

            }
            catch (WebException ex)
            {
                MessageBox.Show("The language pack selected does not exist for this language selection (" + currentdownloadlanguagename + ")");
                //if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
                //{
                //    var resp = (HttpWebResponse)ex.Response;
                //    if (resp.StatusCode == HttpStatusCode.NotFound)
                //    {
                //        string returned2 = client.DownloadString("http://www.microsoft.com/downloads/details.aspx?familyid=" + guid + "&displayLang=" + language);
                //        returned2 = returned2.Substring(returned2.IndexOf("if (g_IsIE) {window.open(\'http://download.microsoft.com") + 26);
                //        returned2 = returned2.Substring(0, returned2.IndexOf("\""));
                //        if (returned2.IndexOf("\'") != -1) returned2 = returned2.Substring(0, returned2.IndexOf("\'"));
                //        returned2 = System.Web.HttpUtility.UrlDecode(returned2);
                //        //MessageBox.Show(returned2);  
                //        ret = returned2;
                //    }
                //}
            }
            return ret;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                for (int i = 0; i <= checkedListBox1.Items.Count - 1; i++)
                {
                    checkedListBox1.SetItemChecked(i, true);
                }
            }
            else
            {
                for (int i = 0; i <= checkedListBox1.Items.Count - 1; i++)
                {
                    checkedListBox1.SetItemChecked(i, false);
                }
            }
        }
    }
}
